<template>
  <div class="map-container">
    <div ref="chart" class="chart" />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const chart = ref(null)
let myChart = null

// 加载地图数据
const loadMapData = async () => {
  const response = await fetch('/heilongjiang-city.json')
  const mapData = await response.json()
  echarts.registerMap('hlj', mapData)
}

// 初始化地图
const initChart = async () => {
  if (!chart.value) return

  myChart = echarts.init(chart.value)

  await loadMapData()

  const option = {
    title: {
      text: '黑龙江省市级地图',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a}<br/>{b}: {c} (个)'
    },
    visualMap: {
      min: 0,
      max: 100,
      inRange: {
        color: ['#f7fbff', '#08306b']
      },
      text: ['高值', '低值'],
      calculable: true
    },
    geo: {
      map: 'hlj',
      roam: true,
      label: {
        emphasis: {
          show: false
        }
      },
      itemStyle: {
        areaColor: '#f2f2f2',
        borderColor: '#444'
      }
    },
    series: [
      {
        name: '示例数据',
        type: 'map',
        map: 'hlj',
        data: [
          { name: '哈尔滨市', value: 10 },
          { name: '齐齐哈尔市', value: 20 },
          { name: '牡丹江市', value: 30 },
          { name: '佳木斯市', value: 40 },
          { name: '大庆市', value: 50 },
          { name: '鸡西市', value: 60 },
          { name: '鹤岗市', value: 70 },
          { name: '双鸭山市', value: 80 },
          { name: '伊春市', value: 90 },
          { name: '七台河市', value: 100 },
          { name: '黑河市', value: 50 },
          { name: '绥化市', value: 30 },
          { name: '大兴安岭地区', value: 20 }
        ]
      }
    ]
  }

  myChart.setOption(option)
}

// 响应窗口大小变化
const resizeChart = () => {
  if (myChart) {
    myChart.resize()
  }
}

onMounted(async () => {
  await initChart()
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
})
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
}
.chart {
  width: 100%;
  height: 600px;
}
</style>
